package com.whmskj.xjlhbc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.dto.QueryDto;
import com.whmskj.xjlhbc.mapper.*;
import com.whmskj.xjlhbc.service.IBy01MaintenanceScheduleService;
import com.whmskj.xjlhbc.service.IMachineInfoService;
import com.whmskj.xjlhbc.service.ISchedulingOfSbbx01MalfunctionRepService;
import com.whmskj.xjlhbc.service.IStopdataInfoHistoryService;
import com.whmskj.xjlhbc.vo.JtKbVo;
import com.whmskj.xjlhbc.vo.RealInfo1Vo;
import com.whmskj.xjlhbc.vo.RealInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MachineInfoServiceImpl extends ServiceImpl<MachineInfoMapper, MachineInfo> implements IMachineInfoService {

    @Autowired
    private RundataInfoMapper rundataInfoMapper;

    @Autowired
    private StopdataInfoMapper stopdataInfoMapper;

    @Autowired
    private PersonnelManagementDataSheetsMapper personnelManagementDataSheetsMapper;

    @Autowired
    private BalanceSheetForSparePartsSbbj01Mapper balanceSheetForSparePartsSbbj01Mapper;

    @Autowired
    private IBy01MaintenanceScheduleService by01MaintenanceScheduleService;

    @Autowired
    private ISchedulingOfSbbx01MalfunctionRepService schedulingOfSbbx01MalfunctionRepService;

    @Autowired
    private IStopdataInfoHistoryService stopdataInfoHistoryService;

    @Autowired
    private SchfzjjMapper schfzjjMapper;

    @Autowired
    private SckyzjjMapper sckyzjjMapper;

    @Autowired
    private ScjsjMapper scjsjMapper;

    @Autowired
    private ScconfigMapper scconfigMapper;

    @Autowired
    private MesjzkMapper mesjzkMapper;

    @Autowired
    private MesjsjMapper mesjsjMapper;

    @Autowired
    private MeszjjMapper meszjjMapper;

    @Override
    public List<MachineInfo> queryList(QueryDto param) {
        return lambdaQuery().list();
    }

    @Override
    public RealInfoVo realInfo(String macid) {
        LambdaQueryWrapper<RundataInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RundataInfo::getMacid,macid);
        RundataInfo rundataInfo = Optional.ofNullable(rundataInfoMapper.selectOne(wrapper)).orElseGet(RundataInfo::new);

        LambdaQueryWrapper<StopdataInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StopdataInfo::getMacid,macid);
        StopdataInfo stopdataInfo = Optional.ofNullable(stopdataInfoMapper.selectOne(queryWrapper)).orElseGet(StopdataInfo::new);

        LambdaQueryWrapper<PersonnelManagementDataSheets> personnelQueryWrapper = new LambdaQueryWrapper<>();
        personnelQueryWrapper.eq(PersonnelManagementDataSheets::getFe1e,rundataInfo.getEmployee());
        PersonnelManagementDataSheets personnel = Optional.ofNullable(personnelManagementDataSheetsMapper.selectOne(personnelQueryWrapper)).orElseGet(PersonnelManagementDataSheets::new);

        int hour = LocalTime.now().getHour();
        boolean zao = hour >= 9 && hour < 21 ;
        RealInfoVo realInfoVo = new RealInfoVo();
        List<RealInfoVo.StopInfo> stopInfoList = realInfoVo.getStopInfoList();

        RealInfoVo.StopInfo stopInfo = new RealInfoVo.StopInfo();
        stopInfo.setType("短纬停");
        stopInfo.setTotal(stopdataInfo.getStopcount_weft_short());
        stopInfo.setStoptime(stopdataInfo.getStoptime_weft_short());
        stopInfoList.add(stopInfo);
        stopInfo = new RealInfoVo.StopInfo();
        stopInfo.setType("长纬停");
        stopInfo.setTotal(stopdataInfo.getStopcount_weft_long());
        stopInfo.setStoptime(stopdataInfo.getStoptime_weft_long());
        stopInfoList.add(stopInfo);
        stopInfo = new RealInfoVo.StopInfo();
        stopInfo.setType("经停");
        stopInfo.setTotal(stopdataInfo.getStopcount_warp());
        stopInfo.setStoptime(stopdataInfo.getStoptime_warp());
        stopInfoList.add(stopInfo);
        stopInfo = new RealInfoVo.StopInfo();
        stopInfo.setType("其他停");
        stopInfo.setTotal(stopdataInfo.getStopcount_other());
        stopInfo.setStoptime(stopdataInfo.getStoptime_other());
        stopInfoList.add(stopInfo);

        stopInfo = realInfoVo.getStopInfo();
        stopInfo.setType("总计");
        stopInfo.setTotal(stopdataInfo.getStopcount_total());
        stopInfo.setStoptime(stopdataInfo.getStoptime_total());

        RealInfoVo.ClassInfo classInfo = realInfoVo.getClassInfo();
        classInfo.setClasses(zao ? "早班" : "晚班");
        classInfo.setTeam(personnel.getClass22());
        classInfo.setGender(personnel.getGender2());
        classInfo.setWorkNumber(personnel.getCode());
        classInfo.setPositions(personnel.getPositions1());
        classInfo.setEmployee(rundataInfo.getEmployee());
        classInfo.setWorktime(zao ? "09:00~21:00" : "21:00~09:00");
        realInfoVo.setRundataInfo(rundataInfo);
        return realInfoVo;
    }

    @Override
    public List<BalanceSheetForSparePartsSbbj01> spareParts(String macid) {
        Page.startPage();
        LambdaQueryWrapper<BalanceSheetForSparePartsSbbj01> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(BalanceSheetForSparePartsSbbj01::getTypeOfEquipmentTied, macid);
        return balanceSheetForSparePartsSbbj01Mapper.selectList(wrapper);
    }

    @Override
    public List<By01MaintenanceSchedule> wb(String macid) {
        LambdaQueryWrapper<By01MaintenanceSchedule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(By01MaintenanceSchedule::getStationNumber1, macid);
        return by01MaintenanceScheduleService.list(wrapper);
    }

    @Override
    public List<SchedulingOfSbbx01MalfunctionRep> gz(String macid) {
        LambdaQueryWrapper<SchedulingOfSbbx01MalfunctionRep> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchedulingOfSbbx01MalfunctionRep::getDeviceNumber, macid);
        return schedulingOfSbbx01MalfunctionRepService.list(wrapper);
    }

    @Override
    public List getZl(String macid, int type) {
        JSONArray hoverData = new JSONArray();
        if(type == 1){//整经
            boolean flag = macid.equals("05") || macid.equals("06");
            String cs = "";
            String jc = "";
            String sd = "";
            String dt = "";
            String dtl = "";
            String cl = "";
            if(flag){
                LambdaQueryWrapper<Sckyzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Sckyzjj::getDevice, macid).orderByDesc(Sckyzjj::getId).last("limit 1");
                Sckyzjj entity = Optional.ofNullable(sckyzjjMapper.selectOne(wrapper)).orElseGet(Sckyzjj::new);
                jc = entity.getA395();
                sd = entity.getA385();
                dt = entity.getA387();
                dtl = entity.getA388();
                cl = entity.getA393();
            }else{
                cs = "华方" ;
                LambdaQueryWrapper<Schfzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Schfzjj::getDevice, macid).orderByDesc(Schfzjj::getId).last("limit 1");
                Schfzjj entity = Optional.ofNullable(schfzjjMapper.selectOne(wrapper)).orElseGet(Schfzjj::new);
                jc = entity.getA301();
                sd = entity.getA303();
                dt = entity.getA305();
                dtl = entity.getA306();
                cl = entity.getA319();
            }
            JSONObject obj = new JSONObject();
            obj.put("key", "设备厂商");
            obj.put("value", cs);
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "状态");
            obj.put("value", "运行");
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "当前经长");
            obj.put("value", jc);
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "当前速度");
            obj.put("value", sd);
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "断头数");
            obj.put("value", dt);
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "断头率");
            obj.put("value", dtl);
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "当班产量");
            obj.put("value", cl);
            hoverData.add(obj);
            return hoverData;
        }
        if(type == 2){//浆纱
            LambdaQueryWrapper<Scjsj> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Scjsj::getDevice, macid).orderByDesc(Scjsj::getId).last("limit 1");
            Scjsj entity = Optional.ofNullable(scjsjMapper.selectOne(wrapper)).orElseGet(Scjsj::new);
            JSONObject obj = new JSONObject();
            obj.put("key", "设备厂商");
            obj.put("value", "恒天重工");
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "状态");
            obj.put("value", "运行");
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "车速");
            obj.put("value", entity.getA217());
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "卷绕转速");
            obj.put("value", entity.getA163());
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "卷绕张力");
            obj.put("value", entity.getA159());
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "前浆槽温度");
            obj.put("value", entity.getA143());
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "后浆槽温度");
            obj.put("value", entity.getA189());
            hoverData.add(obj);
            obj = new JSONObject();
            obj.put("key", "日产量");
            obj.put("value", entity.getA214());
            hoverData.add(obj);
            return hoverData;
        }
        LambdaQueryWrapper<RundataInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RundataInfo::getMacid,macid);
        RundataInfo rundataInfo = Optional.ofNullable(rundataInfoMapper.selectOne(wrapper)).orElseGet(RundataInfo::new);
        JSONObject obj = new JSONObject();
        obj.put("key", "品种");
        obj.put("value", rundataInfo.getVariety());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "看台");
        obj.put("value", rundataInfo.getEmployee());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "状态");
        obj.put("value", rundataInfo.getLoomstate());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "车速");
        obj.put("value", rundataInfo.getSpeed());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "已织长度");
        obj.put("value", rundataInfo.getPiececut_woven());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "当班产量");
        obj.put("value", rundataInfo.getClothlength());
        hoverData.add(obj);
        obj = new JSONObject();
        obj.put("key", "效率");
        obj.put("value", rundataInfo.getEfficiency());
        hoverData.add(obj);
        return hoverData;
    }

    @Override
    public List<RealInfoVo.StopInfo> bytc(String macid) {
        LocalDate end = LocalDate.now();
        LocalDate start = end.withDayOfMonth(1);
        return baseMapper.bytc(macid,start.toString(),end.toString());
    }

    @Override
    public List<StopdataInfoHistory> lstc(String macid, String dateymd) {
        Page.startPage();
        LambdaQueryWrapper<StopdataInfoHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StopdataInfoHistory::getMacid, macid).
                eq(StrUtil.isNotEmpty(dateymd), StopdataInfoHistory::getDateymd, dateymd)
                .orderByDesc(StopdataInfoHistory::getId);
        return stopdataInfoHistoryService.list(wrapper);
    }

    @Override
    public RealInfo1Vo realInfo1(String macid, int type) {
        RealInfo1Vo realInfo1Vo = new RealInfo1Vo();
        String tableName = "jsj";
        Map<String, Object> map = new HashMap<>();
        if(type == 1){//整经
            boolean flag = macid.equals("05") || macid.equals("06");
            if(flag){
                LambdaQueryWrapper<Sckyzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Sckyzjj::getDevice, macid).orderByDesc(Sckyzjj::getId).last("limit 1");
                Sckyzjj entity = Optional.ofNullable(sckyzjjMapper.selectOne(wrapper)).orElseGet(Sckyzjj::new);
                map.putAll(BeanUtil.beanToMap(entity));
                tableName = "ky_zjj";
                realInfo1Vo.setTs(entity.getTs());
            }else{
                LambdaQueryWrapper<Schfzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Schfzjj::getDevice, macid).orderByDesc(Schfzjj::getId).last("limit 1");
                Schfzjj entity = Optional.ofNullable(schfzjjMapper.selectOne(wrapper)).orElseGet(Schfzjj::new);
                map.putAll(BeanUtil.beanToMap(entity));
                tableName = "hf_zjj";
                realInfo1Vo.setTs(entity.getTs());
            }
        }
        if(type == 2){//浆纱
            LambdaQueryWrapper<Scjsj> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Scjsj::getDevice, macid).orderByDesc(Scjsj::getId).last("limit 1");
            Scjsj entity = Optional.ofNullable(scjsjMapper.selectOne(wrapper)).orElseGet(Scjsj::new);
            map.putAll(BeanUtil.beanToMap(entity));
            realInfo1Vo.setTs(entity.getTs());
        }

        LambdaQueryWrapper<Scconfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Scconfig::getTableName, tableName);
        List<Scconfig> scconfigs = scconfigMapper.selectList(wrapper);
        List<RealInfo1Vo.Info> list = scconfigs.stream().map(config -> {
            RealInfo1Vo.Info info = new RealInfo1Vo.Info();
            info.setKey(config.getVarname());
            info.setValue(map.get(config.getColumnName()));
            return info;
        }).collect(Collectors.toList());
        realInfo1Vo.setInfoList(list);
        return realInfo1Vo;
    }

    @Override
    public JtKbVo jtKb() {
        JtKbVo jtKbVo = new JtKbVo();
        JtKbVo.Top left = jtKbVo.getLeft();
        Long count = lambdaQuery().eq(MachineInfo::getLoomstate, "运行").count();
        left.setCount1(Objects.isNull(count) ? "0" : count.toString());
        count = lambdaQuery().eq(MachineInfo::getLoomstate, "临停").count();
        left.setCount2(Objects.isNull(count) ? "0" : count.toString());
        count = lambdaQuery().eq(MachineInfo::getLoomstate, "待机").count();
        left.setCount3(Objects.isNull(count) ? "0" : count.toString());
        count = lambdaQuery().eq(MachineInfo::getLoomstate, "维保").count();
        left.setCount4(Objects.isNull(count) ? "0" : count.toString());
        JtKbVo.Top right = jtKbVo.getRight();

        List<RundataInfo> rundataInfoList = rundataInfoMapper.selectList(null);
        List<RundataInfo> yxList = rundataInfoList.stream().filter(f -> f.getLoomstate().equals("运行")).collect(Collectors.toList());
        count = rundataInfoList.stream().filter(f -> f.getLoomstate().equals("离线")).count();
        left.setCount5(count);
        jtKbVo.getJtList().addAll(rundataInfoList);
        count = (long) yxList.stream().collect(Collectors.groupingBy(RundataInfo::getEmployee)).size();
        right.setCount1(count.toString());
        count = (long) yxList.stream().collect(Collectors.groupingBy(RundataInfo::getVariety)).size();
        right.setCount2(count.toString());
        count = yxList.stream().filter(RundataInfo::isWarpbeamGroundDatetimeToday).count();
        right.setCount3(count.toString());
        double avg = yxList.stream().mapToDouble(RundataInfo::getEfficiency).average().orElse(0.0);
        right.setCount4(String.format("%.2f",avg));
        double sum = yxList.stream().mapToDouble(RundataInfo::getClothlength).sum();
        right.setCount5(String.format("%.2f",sum));
        return jtKbVo;
    }

    @Override
    public JtKbVo jzkkb() {
        JtKbVo jtKbVo = new JtKbVo();
        JtKbVo.Top left = jtKbVo.getLeft();
        JtKbVo.Top right = jtKbVo.getRight();
        List<String> macids = Arrays.asList("01", "02");
        List<List<Object>> jzkList = new ArrayList<>();
        List<Mesjzk> list = new ArrayList<>();
        macids.forEach(macid->{
            LambdaQueryWrapper<Mesjzk> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Mesjzk::getMacid, macid);
            List<Mesjzk> mesjzkList = mesjzkMapper.selectList(wrapper);
            list.addAll(mesjzkList);
            List<Object> jzk = new ArrayList<>(mesjzkList);
            jzkList.add(jzk);
        });
        left.setCount1(list.stream().filter(jzk -> StrUtil.isNotBlank(jzk.getBh()) || StrUtil.isNotBlank(jzk.getZc())).count());
        left.setCount2(list.stream().filter(jzk -> jzk.getMacid().equals("01") && (StrUtil.isNotBlank(jzk.getBh()) || StrUtil.isNotBlank(jzk.getZc()))).count());
        left.setCount3(list.stream().filter(jzk -> jzk.getMacid().equals("02") && (StrUtil.isNotBlank(jzk.getBh()) || StrUtil.isNotBlank(jzk.getZc()))).count());
        left.setCount4(list.stream().filter(jzk -> StrUtil.isBlank(jzk.getBh()) && StrUtil.isBlank(jzk.getZc())).count());
        left.setCount5(String.format("%.2f", (long)left.getCount1() / 120.0 * 100));
        left.setCount6(list.stream().filter(jzk -> StrUtil.isNotBlank(jzk.getRk()) && jzk.getRk().equals(DateUtil.today())).count());
        left.setCount7(list.stream().filter(jzk -> StrUtil.isNotBlank(jzk.getRk()) && DateUtil.betweenDay(DateUtil.parseDate(jzk.getRk()),DateUtil.date(),true) > 30).count());
        right.setCount1(list.stream().mapToLong(jzk-> NumberUtil.parseLong(jzk.getZc(),0L)).sum());
        right.setCount2(list.stream().filter(jzk -> jzk.getMacid().equals("01")).mapToLong(jzk-> NumberUtil.parseLong(jzk.getZc(),0L)).sum());
        right.setCount3(list.stream().filter(jzk -> jzk.getMacid().equals("02")).mapToLong(jzk-> NumberUtil.parseLong(jzk.getZc(),0L)).sum());
        right.setCount4(list.stream().map(Mesjzk::getBh).distinct().count());
        right.setCount5(list.stream().filter(jzk -> jzk.getMacid().equals("01")).map(Mesjzk::getBh).distinct().count());
        right.setCount6(list.stream().filter(jzk -> jzk.getMacid().equals("02")).map(Mesjzk::getBh).distinct().count());
        jtKbVo.getJtList().addAll(jzkList);
        return jtKbVo;
    }

    @Override
    public JtKbVo jszjkb() {
        JtKbVo jtKbVo = new JtKbVo();
        JtKbVo.Top left = jtKbVo.getLeft();
        JtKbVo.Top right = jtKbVo.getRight();
        left.setCount1(7);
        left.setCount2(0);
        left.setCount3(0);
        left.setCount4(0);
        left.setCount5(0);

        List<List<Object>> jzkList = new ArrayList<>();
        LambdaQueryWrapper<Meszjj> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Meszjj::getMacid);
        List<Meszjj> meszjjList = meszjjMapper.selectList(wrapper);
        right.setCount1(meszjjList.stream().mapToLong(m->NumberUtil.parseLong(m.getA393())).sum());
        right.setCount2(meszjjList.stream().mapToLong(m->NumberUtil.parseLong(m.getA305())).sum());
        right.setCount3(meszjjList.stream().mapToLong(m->NumberUtil.parseLong(m.getA306())).sum());
        List<Object> zjj = new ArrayList<>(meszjjList);
        jzkList.add(zjj);

        LambdaQueryWrapper<Mesjsj> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.orderByAsc(Mesjsj::getMacid);
        List<Mesjsj> mesjsjList = mesjsjMapper.selectList(wrapper1);
        right.setCount4(mesjsjList.stream().mapToLong(Mesjsj::getA213).sum());
        right.setCount5(String.format("%.2f",mesjsjList.stream().mapToLong(Mesjsj::getA217).average().orElse(0)));
        right.setCount6(String.format("%.2f",mesjsjList.stream().mapToLong(Mesjsj::getA162).average().orElse(0)));
        List<Object> jsj = new ArrayList<>(mesjsjList);
        jzkList.add(jsj);

        jtKbVo.getJtList().addAll(jzkList);
        return jtKbVo;
    }
}
